#include "PlanTask.h"
#include <QUuid>
#include <QJsonArray>

// ========== TaskArtifacts 序列化 ==========

QJsonObject TaskArtifacts::toJson() const
{
    QJsonObject json;
    json["summary"] = summary;

    QJsonArray linksArray;
    for (const QString& link : evidenceLinks) {
        linksArray.append(link);
    }
    json["links"] = linksArray;

    return json;
}

TaskArtifacts TaskArtifacts::fromJson(const QJsonObject& json)
{
    TaskArtifacts artifacts;
    artifacts.summary = json["summary"].toString();

    // 兼容旧数据：links 可能是字符串或数组
    if (json.contains("links")) {
        if (json["links"].isArray()) {
            QJsonArray linksArray = json["links"].toArray();
            for (const QJsonValue& value : linksArray) {
                artifacts.evidenceLinks.append(value.toString());
            }
        } else if (json["links"].isString()) {
            // 旧数据可能是单个字符串
            QString linkStr = json["links"].toString();
            if (!linkStr.isEmpty()) {
                artifacts.evidenceLinks.append(linkStr);
            }
        }
    }

    return artifacts;
}

// ========== PlanTask 实现 ==========

PlanTask::PlanTask()
    : m_id(QUuid::createUuid().toString())
    , m_status(TaskStatus::Todo)
    , m_hasReminder(false)
    , m_sortOrder(0)
    , m_createdTime(QDateTime::currentDateTime())
    , m_updatedTime(QDateTime::currentDateTime())
{
}

PlanTask::PlanTask(const QString& id, const QString& title)
    : m_id(id)
    , m_title(title)
    , m_status(TaskStatus::Todo)
    , m_hasReminder(false)
    , m_sortOrder(0)
    , m_createdTime(QDateTime::currentDateTime())
    , m_updatedTime(QDateTime::currentDateTime())
{
}

QJsonObject PlanTask::toJson() const
{
    QJsonObject json;
    json["id"] = m_id;
    json["title"] = m_title;
    json["description"] = m_description;
    json["completionNote"] = m_completionNote;
    json["startTime"] = m_startTime.toString(Qt::ISODate);
    json["endTime"] = m_endTime.toString(Qt::ISODate);
    json["completedTime"] = m_completedTime.toString(Qt::ISODate);
    json["status"] = static_cast<int>(m_status);
    json["hasReminder"] = m_hasReminder;
    json["reminderTime"] = m_reminderTime.toString(Qt::ISODate);
    json["sortOrder"] = m_sortOrder;
    json["createdTime"] = m_createdTime.toString(Qt::ISODate);
    json["updatedTime"] = m_updatedTime.toString(Qt::ISODate);

    // [FDD-2025-11] 新增字段
    json["definitionOfDone"] = m_definitionOfDone;
    json["scopeDescription"] = m_scopeDescription;
    json["blockers"] = m_blockers;
    json["artifacts"] = m_artifacts.toJson();

    return json;
}

PlanTask PlanTask::fromJson(const QJsonObject& json)
{
    PlanTask task;
    task.m_id = json["id"].toString();
    task.m_title = json["title"].toString();
    task.m_description = json["description"].toString();
    task.m_completionNote = json["completionNote"].toString();
    task.m_startTime = QDateTime::fromString(json["startTime"].toString(), Qt::ISODate);
    task.m_endTime = QDateTime::fromString(json["endTime"].toString(), Qt::ISODate);
    task.m_completedTime = QDateTime::fromString(json["completedTime"].toString(), Qt::ISODate);
    task.m_status = static_cast<TaskStatus>(json["status"].toInt());
    task.m_hasReminder = json["hasReminder"].toBool();
    task.m_reminderTime = QDateTime::fromString(json["reminderTime"].toString(), Qt::ISODate);
    task.m_sortOrder = json["sortOrder"].toInt();
    task.m_createdTime = QDateTime::fromString(json["createdTime"].toString(), Qt::ISODate);
    task.m_updatedTime = QDateTime::fromString(json["updatedTime"].toString(), Qt::ISODate);

    // [FDD-2025-11] 新增字段（兼容旧数据：缺失时为空）
    task.m_definitionOfDone = json.value("definitionOfDone").toString();
    task.m_scopeDescription = json.value("scopeDescription").toString();
    task.m_blockers = json.value("blockers").toString();

    if (json.contains("artifacts") && json["artifacts"].isObject()) {
        task.m_artifacts = TaskArtifacts::fromJson(json["artifacts"].toObject());
    }

    return task;
}

bool PlanTask::isValid() const
{
    return !m_id.isEmpty() && !m_title.isEmpty();
}

bool PlanTask::isOverdue() const
{
    // [FDD-2025-11] 已完成、已归档的任务不算逾期
    if (m_status == TaskStatus::Done ||
        m_status == TaskStatus::Completed ||
        m_status == TaskStatus::Archived) {
        return false;
    }
    return m_endTime.isValid() && m_endTime < QDateTime::currentDateTime();
}

bool PlanTask::shouldRemindNow() const
{
    // [FDD-2025-11] 已完成、已归档的任务不需要提醒
    if (!m_hasReminder ||
        m_status == TaskStatus::Done ||
        m_status == TaskStatus::Completed ||
        m_status == TaskStatus::Archived) {
        return false;
    }

    QDateTime now = QDateTime::currentDateTime();
    // 提醒时间在当前时间前后1分钟内
    return m_reminderTime.isValid() &&
           qAbs(m_reminderTime.secsTo(now)) <= 60;
}

int PlanTask::getDurationMinutes() const
{
    if (!m_startTime.isValid() || !m_endTime.isValid()) {
        return 0;
    }
    return m_startTime.secsTo(m_endTime) / 60;
}

